package com.gwlc.controller;

import com.gwlc.common.constant.system.RegularExpressionConstant;
import com.gwlc.common.enums.system.user.UserStatusEnum;
import com.gwlc.common.exception.user.NotUsernameException;
import com.gwlc.common.exception.user.NotUsernameOrPasswordException;
import com.gwlc.common.result.Result;
import com.gwlc.common.util.TokenTool;
import com.gwlc.common.util.string.StringTool;
import com.gwlc.system.common.annotation.PermissionAnnotation;
import com.gwlc.system.domain.UserDO;
import com.gwlc.system.domain.dto.PermissionDTO;
import com.gwlc.system.domain.dto.UserDTO;
import com.gwlc.system.domain.dto.UserPermissionDTO;
import com.gwlc.system.domain.dto.UserRoleDTO;
import com.gwlc.system.domain.query.UserQuery;
import com.gwlc.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>lucky-com.gwlc.controller-UserController</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date 2021/8/11
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    /**
     * 获取符合条件的用户信息
     *
     * @param user 用户
     * @return 用户信息
     */
    @RequestMapping("/get_users")
    public Result<List<UserDTO>> getListUsers(UserQuery user) {
        List<UserDTO> users = userService.listUsers(user);
        return Result.ok(users);
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<String> login(String username, String password) {
        //验证用户名
        if (userService.verifyUsername(username)) {
            //验证用户名和密码
            if (userService.verifyUsernameAndPassword(username, password)) {
                UserStatusEnum.verifyUserStatus(userService.getUserStatusByUsername(username));
                return Result.okOrFailed(userService.setUserToken(username, password, TokenTool.createToken()), "登录成功", "登录失败");
            } else {
                throw new NotUsernameOrPasswordException();
            }
        } else {
            throw new NotUsernameException();
        }
    }

    /**
     * 注册账号
     *
     * @param username 用户名
     * @param password 密码
     * @param nickname 昵称
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<String> register(String username, String password, String nickname) {

        if (username == null) {
            return Result.failed("用户名不能为空");
        }
        if (password == null) {
            return Result.failed("密码不能为空");
        }
        if (!StringTool.verifyRegularExpression(RegularExpressionConstant.USER_NAME_VERIFY, username)) {

            return Result.failed("用户名不符合要求,字母开头，允许5-16字节，允许字母数字下划线");
        }
        if (!StringTool.verifyRegularExpression(RegularExpressionConstant.USER_PASSWORD_VERIFY, password)) {

            return Result.failed("密码不符合要求,以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
        }

        if (userService.verifyUsername(username)) {
            return Result.failed("用户名已存在");
        }
        UserQuery user = new UserQuery();
        user.setUserName(username);
        user.setUserPassword(password);
        user.setUserNickname(nickname);
        return Result.okOrFailed(userService.saveUser(user), "注册成功", "注册失败");
    }

    /**
     * 修改密码
     *
     * @param request     请求
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 结果
     */
    @PermissionAnnotation
    @PostMapping("/changePassword")
    public Result<String> changePassword(HttpServletRequest request, String oldPassword, String newPassword) {
        if (oldPassword == null) {
            return Result.failed("旧密码不能为空");
        }
        if (newPassword == null) {
            return Result.failed("新密码不能为空");
        }
        if (!StringTool.verifyRegularExpression(RegularExpressionConstant.USER_PASSWORD_VERIFY, oldPassword)) {

            return Result.failed("旧密码不符合要求,以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
        }
        if (!StringTool.verifyRegularExpression(RegularExpressionConstant.USER_PASSWORD_VERIFY, newPassword)) {

            return Result.failed("新密码不符合要求,以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
        }
        String token = request.getHeader("token");
        UserQuery user = new UserQuery();
        user.setUserToken(token);
        user.setUserPassword(oldPassword);

        UserDTO userDTO = userService.getUser(user);
        if (userDTO.getUserId() != null && userDTO.getUserId() > 0) {
            Long userId = userDTO.getUserId();
            UserQuery userQuery = new UserQuery();
            userQuery.setUserId(userId);
            userQuery.setUserPassword(newPassword);
            return Result.okOrFailed(userService.updateUser(userQuery), "密码修改成功", "密码修改失败");
        } else {
            return Result.failed("旧密码输入错误");
        }

    }

    /**
     * 修改用户信息
     *
     * @param request      请求
     * @param userNickname 用户昵称
     * @return 结果
     */
    @PermissionAnnotation
    @PostMapping("changeUser")
    public Result<String> changeUser(HttpServletRequest request, String userNickname) {

        String token = request.getHeader("token");
        if (userNickname == null || userNickname.isEmpty()) {
            return Result.failed("修改失败");
        }
        UserDO userDO = userService.getUserByToken(token);
        userDO.setUserNickname(userNickname);


        return Result.okOrFailed(userService.updateUser(new UserQuery(userDO)), "修改成功", "修改失败");
    }

    /**
     * 获取单个用户权限信息
     *
     * @param request 连接
     * @return 用户权限信息
     */
    @PermissionAnnotation
    @PostMapping("/get_user_permission")
    public Result<UserPermissionDTO> getUserPermission(HttpServletRequest request) {
        String token = request.getHeader("token");
        UserDO user = new UserDO();
        user.setUserToken(token);
        return Result.ok(userService.getUserPermission(user));
    }

    /**
     * 获取单个用户角色信息
     *
     * @param request 连接
     * @return 用户角色信息
     */
    @PermissionAnnotation
    @PostMapping("/get_user_role")
    public Result<UserRoleDTO> getUserRole(HttpServletRequest request) {
        String token = request.getHeader("token");
        UserDO user = new UserDO();
        user.setUserToken(token);
        return Result.ok(userService.getUserRole(user));
    }

    /**
     * 授权
     *
     * @param userId      用户id
     * @param permissions 授予的权限
     * @return 结果
     */
    @PermissionAnnotation("give_permission")
    @PostMapping("/give_user_permissions")
    public Result<String> giveUserPermissions(Long userId, List<PermissionDTO> permissions) {


        return Result.ok();
    }
}
